/**
 * MessageBroker 使用示例
 * 展示如何在不同环境中使用 MessageBroker
 */

import { createMessageBroker, MessageBrokerPresets } from '../factories/message-broker.factory';
import { ChatMessage, ChatMode } from '../types';

/**
 * 开发环境使用示例
 */
export async function developmentExample() {
  console.log('=== 开发环境示例 ===');

  // 创建开发环境的 MessageBroker（使用模拟实现）
  const messageBroker = await createMessageBroker(
    MessageBrokerPresets.development({
      responseDelay: 200,
      chunkDelay: 50,
      executionDelay: 300
    })
  );

  // 发送非流式消息
  const message: ChatMessage = {
    content: 'Hello, this is a development test!',
    role: 'user'
  };

  try {
    console.log('发送非流式消息...');
    const response = await messageBroker.sendMessage(message, {
      streaming: false,
      mode: ChatMode.CHAT
    });
    console.log('响应:', response);

    // 发送流式消息
    console.log('\n发送流式消息...');
    const streamMessage: ChatMessage = {
      content: 'Stream this message please',
      role: 'user'
    };

    const streamResponse = await messageBroker.sendMessage(streamMessage, {
      streaming: true,
      mode: ChatMode.CHAT
    });

    console.log('流式响应:');
    for await (const chunk of streamResponse as AsyncIterable<any>) {
      console.log('  -', chunk.type, chunk.node?.type || chunk.state || chunk.error);
    }

    // 工具使用示例
    console.log('\n工具使用示例...');
    const toolResult = await messageBroker.handleToolUse('view', {
      path: 'example.ts'
    });
    console.log('工具结果:', toolResult);

    // 记忆操作示例
    console.log('\n记忆操作示例...');
    const memoryResult = await messageBroker.handleMemoryOperation('save', {
      content: 'This is an important fact to remember'
    });
    console.log('记忆保存结果:', memoryResult);

  } catch (error) {
    console.error('错误:', error);
  } finally {
    messageBroker.dispose();
  }
}

/**
 * 测试环境使用示例
 */
export async function testExample() {
  console.log('\n=== 测试环境示例 ===');

  // 创建快速测试配置的 MessageBroker
  const messageBroker = await createMessageBroker(MessageBrokerPresets.fastTest());

  const message: ChatMessage = {
    content: 'Quick test message',
    role: 'user'
  };

  try {
    const startTime = Date.now();
    const response = await messageBroker.sendMessage(message, { streaming: false });
    const endTime = Date.now();

    console.log(`快速响应 (${endTime - startTime}ms):`, response);

  } catch (error) {
    console.error('测试错误:', error);
  } finally {
    messageBroker.dispose();
  }
}

/**
 * 错误处理示例
 */
export async function errorHandlingExample() {
  console.log('\n=== 错误处理示例 ===');

  // 创建会失败的 MessageBroker
  const messageBroker = await createMessageBroker(
    MessageBrokerPresets.development({
      shouldFail: true,
      responseDelay: 100
    })
  );

  const message: ChatMessage = {
    content: 'This should fail',
    role: 'user'
  };

  try {
    await messageBroker.sendMessage(message, { streaming: false });
  } catch (error) {
    console.log('预期的错误被正确捕获:', error instanceof Error ? error.message : `${error}`);
  }

  messageBroker.dispose();
}

/**
 * 事件监听示例
 */
export async function eventListeningExample() {
  console.log('\n=== 事件监听示例 ===');

  const messageBroker = await createMessageBroker(MessageBrokerPresets.development());

  // 设置事件监听器
  messageBroker.on('messageStart', (data) => {
    console.log('消息开始:', data.messageId);
  });

  messageBroker.on('messageComplete', (data) => {
    console.log('消息完成:', data.messageId);
  });

  messageBroker.on('toolUseStart', (data) => {
    console.log('工具开始执行:', data.toolName);
  });

  messageBroker.on('toolUseComplete', (data) => {
    console.log('工具执行完成:', data.toolName);
  });

  const message: ChatMessage = {
    content: 'Message with event tracking',
    role: 'user'
  };

  try {
    await messageBroker.sendMessage(message, { streaming: false });
    await messageBroker.handleToolUse('echo', { message: 'test' });
  } catch (error) {
    console.error('事件示例错误:', error);
  } finally {
    messageBroker.dispose();
  }
}

/**
 * 运行所有示例
 */
export async function runAllExamples() {
  try {
    await developmentExample();
    await testExample();
    await errorHandlingExample();
    await eventListeningExample();

    console.log('\n=== 所有示例执行完成 ===');
  } catch (error) {
    console.error('示例执行失败:', error);
  }
}

// 如果直接运行此文件，执行所有示例
if (require.main === module) {
  runAllExamples().catch(console.error);
}
